package com.zhang.third.day09;

import com.zhang.third.utils.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * @title: 使用CEP实现订单超时
 * @author: zhang
 * @date: 2022/4/13 11:32
 */
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Event> stream = env
                .fromElements(
                        new Event("order-1", "create", 1000L),
                        new Event("order-2", "create", 2000L),
                        new Event("order-1", "pay", 3000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        Pattern<Event, Event> pattern = Pattern
                .<Event>begin("order")
                .where(new SimpleCondition<Event>() {
                    @Override
                    public boolean filter(Event value) throws Exception {
                        return value.value.equals("create");
                    }
                })
                .next("pay")
                .where(new SimpleCondition<Event>() {
                    @Override
                    public boolean filter(Event value) throws Exception {
                        return value.value.equals("pay");
                    }
                })
                .within(Time.seconds(5));

        SingleOutputStreamOperator<String> result = CEP
                .pattern(stream.keyBy(r -> r.key), pattern)
                .flatSelect(
                        new OutputTag<String>("timeout") {
                        },
                        // 发送超时信息的匿名类
                        new PatternFlatTimeoutFunction<Event, String>() {
                            @Override
                            public void timeout(Map<String, List<Event>> map, long timeoutTimestamp, Collector<String> out) throws Exception {
                                Event order = map.get("order").get(0);
                                // 将超时数据发送到侧输出流
                                out.collect("订单" + order.key + "超时未支付");
                            }
                        },
                        // 处理正常匹配的数据
                        new PatternFlatSelectFunction<Event, String>() {
                            @Override
                            public void flatSelect(Map<String, List<Event>> map, Collector<String> out) throws Exception {
                                Event order = map.get("order").get(0);
                                Event pay = map.get("pay").get(0);
                                out.collect("订单" + order.key + "正常支付，订单创建时间是：" +
                                        order.ts + ",支付时间是：" + pay.ts);
                            }
                        }
                );
        result.getSideOutput(new OutputTag<String>("timeout") {
        }).print("侧输出流");
        result.print("主流");

        env.execute();
    }
}
